<template>
  <div class="page-container">
    <!-- 顶部导航栏 -->
    <TopNav />

    <!-- 页面主体内容 -->
    <div class="card-container">
     <el-card class="full-height-card" shadow="always">
        <template #header>
          <div>
            <h2>设置下属单位信息</h2>
          </div>
        </template>
        <div class="table-wrapper">
          <el-table :data="unitList" border class="full-height-table"
            :header-cell-style="{ background: '#f0f0f0' }">
            <el-table-column prop="code" label="单位代码" align="center">
              <template #default="scope">
                <el-input 
                  v-if="isEditable(scope.$index)" 
                  v-model="scope.row.code" 
                />
                <span v-else>{{ scope.row.code }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="单位名称" align="center">
              <template #default="scope">
                <el-input 
                  v-if="isEditable(scope.$index)" 
                  v-model="scope.row.name" 
                />
                <span v-else>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.status" 
                  placeholder="请选择" 
                  :disabled="!isEditable(scope.$index)"
                >
                  <el-option label="启用" value="启用" />
                  <el-option label="停用" value="停用" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="删除" align="center">
              <template #default="scope">
                <el-button 
                  size="large" 
                  :icon="Delete" 
                  @click="handleDelete(scope.$index)" 
                  :disabled="!isEditable(scope.$index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
   
        <!-- 底部操作按钮 -->
        <template #footer>
          <div class="action-buttons">
            <!-- 新增模式下显示还原按钮 -->
            <el-button 
              v-if="editMode === 'add'" 
              type="warning" 
              size="large" 
              style="font-size: 16px" 
              @click="handleRevert"
            >
              还原
            </el-button>
            
            <!-- 修改模式下显示还原按钮（替代新增按钮） -->
            <el-button 
              v-if="editMode === 'edit'" 
              type="warning" 
              size="large" 
              style="font-size: 16px" 
              @click="handleRevert"
            >
              还原
            </el-button>
            
            <!-- 初始状态显示新增按钮 -->
            <el-button 
              v-if="!editMode" 
              type="success" 
              size="large" 
              style="font-size: 16px" 
              @click="handleAdd"
            >
              新增
            </el-button>
            
            <!-- 新增模式下保持新增按钮 -->
            <el-button 
              v-if="editMode === 'add'" 
              type="success" 
              size="large" 
              style="font-size: 16px" 
              @click="handleAdd"
            >
              新增
            </el-button>
            
            <!-- 修改按钮 -->
            <el-button 
              v-if="!editMode"
              type="success" 
              size="large" 
              style="font-size: 16px" 
              @click="handleEdit"
            >
              修改
            </el-button>

            <!-- 保存按钮 -->
            <el-button 
              v-if="editMode"
              type="primary" 
              size="large" 
              style="font-size: 16px" 
              @click="handleSave"
            >
             保存
            </el-button>
            
            <!-- 导出Word按钮 -->
            <!-- <el-button 
              type="success" 
              size="large" 
              style="font-size: 16px"
            >
              导出Word
            </el-button> -->
          </div>
        </template>
      </el-card>
    </div>
  </div>
</template>

<script setup>
// 引入组件
import TopNav from './navmenu.vue'
import { onMounted, ref } from 'vue'
import { Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import dbClient from '../../utils/database.js'

// 原始数据备份
const originalUnitList = ref([])
// 响应式数据
const unitList = ref([]);
const editMode = ref(null) // null: 初始状态, 'add': 新增模式, 'edit': 修改模式
const backupData = ref([]) // 备份数据用于还原
const newRowIndices = ref([]) // 记录新增行的索引

onMounted(() =>{
  getOriginalUnitList();
})

// 从数据库获取下属单位列表
const getOriginalUnitList = async () => {
  try {
    const data = await dbClient.query('SELECT * FROM subUnits ORDER BY created_at DESC');
    originalUnitList.value = data.map(item => ({
      id: item.id,
      code: item.code,
      name: item.name,
      status: item.status
    }));
    unitList.value = [...originalUnitList.value];
  } catch (error) {
    console.error('获取下属单位列表失败:', error);
    ElMessage.error('获取下属单位列表失败: ' + error.message);
    unitList.value = [...originalUnitList.value];
  }
}


// 判断行是否可编辑
const isEditable = (index) => {
  if (editMode.value === 'add') {
    // 新增模式下只有新增的行可编辑
    return newRowIndices.value.includes(index)
  } else if (editMode.value === 'edit') {
    // 修改模式下所有行可编辑
    return true
  }
  // 初始状态不可编辑
  return false
}

// 进入新增模式
const handleAdd = () => {
  if (!editMode.value) {
    editMode.value = 'add'
    // 备份当前数据
    backupData.value = JSON.parse(JSON.stringify(unitList.value))
    newRowIndices.value = []
  }
  
  // 添加新行
  const newRowIndex = unitList.value.length
  unitList.value.push({
    code: '',
    name: '',
    status: ''
  })
  newRowIndices.value.push(newRowIndex)
}

// 进入修改模式
const handleEdit = () => {
  if (!editMode.value) {
    editMode.value = 'edit'
    console.log(editMode.value)
    // 备份当前数据
    backupData.value = JSON.parse(JSON.stringify(unitList.value))
  }
}

// 还原数据到最初状态
const handleRevert = async () => {
  editMode.value = null
  newRowIndices.value = []
  // 重新从数据库查询最新数据
  await getOriginalUnitList()
}

// 保存数据
const handleSave = async () => {
  // 验证数据
  const invalidRows = unitList.value.filter(row => 
    !row.code || !row.name || !row.status
  )
  
  if (invalidRows.length > 0) {
    ElMessage.error('请填写完整的单位代码、单位名称和状态')
    return
  }

  try {
    // 批量处理数据：新增的插入，已有的更新
    const dbOperations = unitList.value.map(row => {
      if (row.id) {
        // 已有数据，执行更新操作
        return dbClient.update(
          'UPDATE subUnits SET code = ?, name = ?, status = ? WHERE id = ?',
          [row.code, row.name, row.status, row.id]
        );
      } else {
        // 新增数据，执行插入操作
        return dbClient.insert(
          'INSERT INTO subUnits (code, name, status) VALUES (?, ?, ?)',
          [row.code, row.name, row.status]
        );
      }
    });
    
    await Promise.all(dbOperations);
    
    ElMessage.success('保存成功');
    // 保存后退出编辑模式，保留新增的数据
    backupData.value = JSON.parse(JSON.stringify(unitList.value));
    editMode.value = null;
    newRowIndices.value = [];
    
    // 刷新数据
    await getOriginalUnitList();
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error(`保存失败: ${error.message}`);
  }
}

// 删除行
const handleDelete = async (index) => {
  const row = unitList.value[index]
  
  if (row.id) {
    // 已有数据，从数据库中删除
    try {
      await dbClient.delete(
        'DELETE FROM subUnits WHERE id = ?',
        [row.id]
      )
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(`删除失败: ${error.message}`)
      return // 如果数据库删除失败，不执行前端删除
    }
  } else {
    // 新增的空白行，只从前端删除
    ElMessage.success('已移除')
  }
  
  // 从记录中移除索引
  newRowIndices.value = newRowIndices.value.filter(i => i !== index)
  // 调整剩余新增行的索引
  newRowIndices.value = newRowIndices.value.map(i => i > index ? i - 1 : i)
  // 删除行
  unitList.value.splice(index, 1)
}

</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f6f7;
}

.card-container {
  flex: 1;
  padding: 10px;
  box-sizing: border-box;
}

/* 卡片：占满容器高度 */
.full-height-card {
  height: 99%;
  display: flex;
  flex-direction: column;
  background: #f5f6f7; /* 浅灰色背景 */
  margin: 10px;

}

/* 头部区域 */
:deep(.el-card__header) {
  min-height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  flex-shrink: 0;
  background: white;
}

/* 卡片主体内容区域：占据剩余空间 */
:deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  background: #f5f6f7; /* 浅灰色背景 */
}

/* 表格容器：自适应高度 */
.table-wrapper {
  margin: 20px 20px;
  background: white; /* 表格区域白色背景 */
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  max-height: calc(100vh - 300px); /* 计算可用高度（减去导航栏、卡片头和按钮栏的高度） */
  overflow-y: auto; /* 垂直滚动 */
}

/* 表格：自适应高度 */
.full-height-table {
  width: 100%;
}

/* 底部按钮区域 */
:deep(.el-card__footer) {
  min-height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  border-top: 1px solid #eee;
  flex-shrink: 0;
  background: white;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  width: 100%;
}

/* 表头字体加粗样式 */
:deep(.el-table__header th .cell) {
  font-weight: bold;
  font-size: 18px;
  color: #1d1d1da9;
}

:deep(.el-table__body td .cell) {
  font-size: 18px;
}

/* 输入框样式调整 */
:deep(.el-input__wrapper) {
  width: 120px;
}
.card-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
  color: #333;
}
</style>